<template>
  <van-field
    :label="label"
    label-align="top"
    :model-value="modelValue"
    readonly
    :placeholder="`请选择${label}`"
    @click="onShowDatePicker"
  />
  <van-popup v-model:show="showDatePicker" position="bottom" teleport="body" style="height: 60vh">
    <van-picker-group
      confirm-button-text="确认日期"
      :title="label"
      :tabs="pickerTabs"
      @confirm="onConfirm"
      @cancel="onCancel"
    >
      <template #cancel>
        <span style="color: #ee0a24">清空日期</span>
      </template>
      <van-date-picker v-model="startDate" />
      <van-time-picker v-if="isDataTime" v-model="startTime" :columns-type="columnsType" />
      <van-date-picker v-model="endDate" />
      <van-time-picker v-if="isDataTime" v-model="endTime" :columns-type="columnsType" />
    </van-picker-group>
  </van-popup>
</template>

<script setup lang="ts">
import { getDate } from '@/framework/utils/common'
import { showError } from '@/framework/common/notify'
import { TimePickerColumnType } from 'vant'

const DATE = 'date' as const
const DATE_TIME = 'dateTime' as const
const columnsType = ['hour', 'minute', 'second'] as Array<TimePickerColumnType>

const props = withDefaults(
  defineProps<{
    label: string
    dateRange: [string, string]
    type?: typeof DATE | typeof DATE_TIME
  }>(),
  {
    type: 'date'
  }
)

const { label, type } = toRefs(props)
const isDataTime = computed(() => type.value === DATE_TIME)
const pickerTabs = computed(() =>
  isDataTime.value ? ['开始日期', '开始时间', '结束日期', '结束时间'] : ['开始日期', '结束日期']
)

const emit = defineEmits<{
  (e: 'update:dateRange', value: [string, string] | []): void
}>()

let showDatePicker = ref(false)
const startDate: Ref<Array<string>> = ref([])
const endDate: Ref<Array<string>> = ref([])
const startTime: Ref<Array<string>> = ref([])
const endTime: Ref<Array<string>> = ref([])
const _dateRange: Ref<[string, string] | []> = ref([])

const modelValue = computed(() => {
  if (!_dateRange.value.length) return ''
  let [startTimeStr, endTimeStr] = _dateRange.value as unknown as [string, string]
  if (isDataTime.value) return startTimeStr + ' 至 ' + endTimeStr
  return startTimeStr.split(' ')[0] + ' 至 ' + endTimeStr.split(' ')[0]
})

const setTimeDefault = (target: Ref, value: string[]) => {
  if (!target.value || !target.value.length) target.value = value
}

const onShowDatePicker = () => {
  showDatePicker.value = true
  const date = getDate().split('-')
  setTimeDefault(startDate, date)
  setTimeDefault(endDate, date)
  setTimeDefault(startTime, ['00', '00', '00'])
  setTimeDefault(endTime, ['23', '59', '59'])
}

const onConfirm = () => {
  let isLegal = true
  // 比较开始日期和结束日期是否合法
  for (let i = 0, len = startDate.value.length; i < len; ++i) {
    if (+startDate.value[i] > +endDate.value[i]) {
      isLegal = false
      showError('开始日期不能大于结束日期！')
      break
    }
  }
  const startDateStr = startDate.value.join('-')
  const endDateStr = endDate.value.join('-')
  const startTimeStr = startTime.value.join(':')
  const endTimeStr = endTime.value.join(':')
  // 只有日期相同的情况下，才有必要比较开始时间和结束时间
  if (startDateStr === endDateStr) {
    // 比较开始时间和结束时间是否合法
    for (let i = 0, len = startTime.value.length; i < len; ++i) {
      if (+startTime.value[i] > +endTime.value[i]) {
        isLegal = false
        showError('开始时间不能大于结束时间！')
        break
      }
    }
  }
  if (isLegal) {
    _dateRange.value = [`${startDateStr} ${startTimeStr}`, `${endDateStr} ${endTimeStr}`]
    showDatePicker.value = false
  }
}

const onCancel = () => {
  showDatePicker.value = false
  _dateRange.value = []
}

watch(
  () => _dateRange.value,
  (value) => emit('update:dateRange', value)
)
</script>

<style scoped></style>
